﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Grids;
using VAdvantage.Editor;
using VAdvantage.Logging;
using VAdvantage.Model;
using VAdvantage.UIEvent;
using VAdvantage.Utility;
using System.Windows.Data;

namespace VAdvantage.Controls
{
    public partial class VURL : UserControl, IControl, IContextMenuListener, IEditingControl
    {

        #region "Declaration"

        /**	Logger	*/
        private static VLogger log = null;
        /** Column Name				*/
        private String _columnName;
        /** The Text				*/
        private bool _readOnly;
        private bool _mandatory;
        /** The Button              */
        /**	Popup Menu				*/
        ContextMenuStrip _popupMenu = null;
        /** Editor Menu Item		*/
        //private ToolStripMenuItem mEditor;
        /** Grid Field				*/
        private GridField _mField = null;

        private String _oldText;
        private String _initialText;
        /**	Setting new value			*/
        private volatile bool _setting = false;
        /** Field Length				*/
        private int _fieldLength;

        private int _displayLength;
        private int _displayType;

        private Binding binding = null;

        #endregion

        /// <summary>
        /// URL
        /// </summary>
        public VURL()
        {
            InitializeComponent();
            //txtUrl.ContextMenuStrip = _popupMenu;

            //btnUrl.Image = Utility.Env.GetImageIcon("Online10.gif");	//	should be 10
            //btnUrl.TabStop = false;

        }

        /// <summary>
        /// URL 
        /// </summary>
        /// <param name="columnName"></param>
        /// <param name="mandatory"></param>
        /// <param name="isReadOnly"></param>
        /// <param name="isUpdateable"></param>
        /// <param name="displayLength"></param>
        /// <param name="fieldLength"></param>
        /// 
        public VURL(String columnName, bool mandatory, bool isReadOnly, bool isUpdateable,
        int displayLength, int fieldLength)
            : this()
        {
            //this.Name = columnName;
            _columnName = columnName;
            _fieldLength = fieldLength;
            _displayLength = displayLength;
            _mandatory = mandatory;
            txtUrl.IsReadOnly = isReadOnly;
            log = VLogger.GetVLogger(typeof(VURL).FullName);

            //	***	Text	***
            txtUrl.MaxLength = fieldLength;

            // this.Width = displayLength < 30 ? 300 : 500;

            //m_text.setFocusable(true);

            //	Background
            SetIsMandatory(mandatory);
            //	***	Button	***


            //	Prefereed Size
            // this.Width = 300;
            //	ReadWrite
            if (isReadOnly || !isUpdateable)
                SetReadOnly(true);
            else
                SetReadOnly(false);

            //txtUrl.ContextMenuStrip = _popupMenu;
            //	Popup for Editor

            if (!DataBase.GlobalVariable.IsVisualEditor)
            {
                this.btnUrl.Click += new RoutedEventHandler(btnUrl_Click);
                this.txtUrl.KeyUp += new KeyEventHandler(txtUrl_KeyUp);
                this.txtUrl.TextChanged += new TextChangedEventHandler(txtUrl_TextChanged);
                SetPopup();
            }
            else
            {
                //this.txtUrl.MouseDown += new MouseEventHandler(txtUrl_MouseDown);
                //this.txtUrl.MouseMove += new MouseEventHandler(txtUrl_MouseMove);
                //this.txtUrl.MouseUp += new MouseEventHandler(txtUrl_MouseUp);
                //this.txtUrl.MouseEnter += new EventHandler(txtUrl_MouseEnter);
            }

            //  Popup
            // }
            //this.DataBindings.DefaultDataSourceUpdateMode = DataSourceUpdateMode.Never;
        }


        public static readonly DependencyProperty ValueChangedProperty =
      DependencyProperty.Register("Value", typeof(String), typeof(VAdvantage.Controls.VURL), new PropertyMetadata((o, e) =>
      {
          ((VURL)o).SetValue((Object)e.NewValue);

      }));


        public Object Value
        {
            get
            {
                return ((VURL)GetValue(VTextBox.ValueChangedProperty));
            }
            set
            {
                SetValue(VURL.ValueChangedProperty, value);
            }
        }


        public String Text
        {
            get
            {
                return txtUrl.Text;
            }
            set
            {
                txtUrl.Text = value;
            }
        }

        void txtUrl_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!_setting)
            {

                if (this.Text.Equals(_oldText))
                {
                    return;
                }


                SetColor();
                if (EditingControlDataGridView != null)
                {
                    EditingControlDataGridView.RaiseCellValueChanged(this);
                    _mField.SetValue(this.Text);
                    ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), this.Text);
                }
                else
                {
                    if (VetoableChangeListener != null)
                    {
                        VetoableChangeListener(this, EventArgs.Empty);
                    }
                }
            }
        }

        void txtUrl_KeyUp(object sender, KeyEventArgs e)
        {
            _setting = true;
            try
            {
                String clear = GetText();
                if (clear.Length > _fieldLength)
                    clear = clear.Substring(0, _fieldLength);
                //fireVetoableChange(m_columnName, m_oldText, clear);
                txtUrl.Text = clear;
            }
            catch
            {
            }
            _setting = false;
        }

        void btnUrl_Click(object sender, RoutedEventArgs e)
        {
            String urlString = txtUrl.Text.Trim();// m_text.getText();
            String message = null;
            if (urlString != null && urlString.Length > 0)
            {
                try
                {
                    Envs.StartBrowser(urlString);
                    return;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }
            Classes.ShowMessage.Warn("URLnotValid", null, message, "");
        }

        /// <summary>
        /// Set Pop Up
        /// </summary>
        private void SetPopup()
        {

            if (_fieldLength > _displayLength)
            {
                _popupMenu = new ContextMenuStrip();
                _popupMenu.AddMenuListener(this);

                MenuItem menuEditor = new MenuItem();
                menuEditor.Header = Msg.GetMsg(Utility.Envs.GetCtx(), "Editor");
                menuEditor.Icon = Envs.LoadImageSource("Editor16.png");
                menuEditor.Click += delegate
                {
                    OnMenu(new ContextMenuEvent("Editor"));
                };

                _popupMenu.Items.Add(menuEditor);
            }
        }

        #region "IControl"
        /// <summary>
        /// Display Type of field
        /// </summary>
        /// <returns></returns>
        public int GetDisplayType()
        {
            return _displayType;
        }

        /// <summary>
        /// Set DisplayType
        /// </summary>
        /// <param name="displayType">int displaytype</param>
        public void SetDisplayType(int displayType)
        {
            _displayType = displayType;
        }

        /// <summary>
        /// is mandatory
        /// </summary>
        /// <returns>true if mandatory</returns>
        public bool GetIsMandatory()
        {
            return _mandatory;
        }

        /// <summary>
        /// is read only
        /// </summary>
        /// <returns>true if read only</returns>
        public bool GetIsReadonly()
        {
            return _readOnly;

        }

        /// <summary>
        /// field object of control
        /// </summary>
        /// <returns>GridField Object</returns>
        public GridField GetField()
        {
            return _mField;
        }

        /// <summary>
        /// Set field object
        /// </summary>
        /// <param name="mField"></param>
        public void SetField(GridField mField)
        {
            _mField = mField;
            if (_mField != null
                && MRole.GetDefault().IsShowPreference())
            {
                if (_popupMenu == null)
                {
                    _popupMenu = new ContextMenuStrip();
                    _popupMenu.AddMenuListener(this);
                }
                Framework.ValuePreference.AddPreferenceMenuItem(null, _popupMenu);
            }

            if (_popupMenu != null)
            {
                ContextMenuService.SetContextMenu(txtUrl, _popupMenu);
            }
        }   //  setField

        /// <summary>
        /// get Name of Object
        /// </summary>
        /// <returns></returns>
        public string GetName()
        {
            return _columnName;
        }

        /// <summary>
        /// Get value 
        /// </summary>
        /// <returns></returns>
        public object GetValue()
        {
            return txtUrl.Text;
        }

        /// <summary>
        /// Get Text
        /// </summary>
        /// <returns>string text</returns>
        public string GetText()
        {
            return this.txtUrl.Text;
        }

        /// <summary>
        /// Set value Of control
        /// </summary>
        /// <param name="value"></param>
        public void SetValue(object value)
        {

            if (value == null)
                _oldText = "";
            else
                _oldText = value.ToString();
            //	only set when not updated here
            //if (_setting)
            //   return;
            this.txtUrl.Text = _oldText;
            _initialText = _oldText;
            SetColor();
            //	If R/O left justify 
            //if (!txtUrl.ReadOnly _text.isEditable() || !isEnabled())
            //    m_text.setCaretPosition(0);
        }

        /// <summary>
        /// Set IsMandatory
        /// </summary>
        /// <param name="value"></param>
        public void SetIsMandatory(bool value)
        {
            _mandatory = value;
        }

        private SolidColorBrush backColor = new SolidColorBrush(Colors.White);

        /// <summary>
        /// Set Is readonly
        /// </summary>
        /// <param name="readOnly"></param>
        public void SetReadOnly(bool readOnly)
        {
            _readOnly = readOnly;
            if (readOnly)
            {
                this.txtUrl.IsReadOnly = true;
                btnUrl.IsEnabled = false;
                backColor.Color = DataBase.GlobalVariable.READONLY_TEXT_BACK_COLOR;
                this.txtUrl.Background = backColor;
            }
            else
            {
                txtUrl.IsReadOnly = false;
                btnUrl.IsEnabled = true;
                backColor.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                this.txtUrl.Background = backColor;
                SetColor();
            }
        }

        /// <summary>
        /// Set Back color to mandatory color 
        /// </summary>
        private void SetColor()
        {
            if (_mandatory && !_readOnly)
            {
                if (this.txtUrl.Text.Trim() == "")
                {
                    backColor.Color = DataBase.GlobalVariable.MANDATORY_TEXT_BACK_COLOR;
                    this.txtUrl.Background = backColor;
                    return;
                }
                backColor.Color = DataBase.GlobalVariable.NORMAL_TEXT_BACK_COLOR;
                this.txtUrl.Background = backColor;
                if (_mField != null)
                    _mField.SetError(false);
            }
        }

        public void SetBackGround(bool value)
        {


        }

        /// <summary>
        /// Bindable proprty of control
        /// </summary>
        public String BindValue
        {
            set
            {
                binding = new Binding(value);
                binding.Mode = BindingMode.OneWay;
                this.SetBinding(VURL.ValueChangedProperty, binding);
            }
        }

        public event EventHandler VetoableChangeListener;
        private bool _focus;

        public void SetName(string name)
        {
            _columnName = name;
        }

        public bool IsDisabled()
        {
            return !this.IsEnabled;
        }

        public void SetDisabled(bool disabled)
        {
            this.IsEnabled = !disabled;
        }

        public int GetTabIndex()
        {
            return this.TabIndex;
        }

        public void SetTabindex(int tabindex)
        {
            this.TabIndex = tabindex;
        }

        public bool Multiline
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public bool Visible
        {
            get
            {
                return this.Visibility == System.Windows.Visibility.Visible;
            }
            set
            {
                this.Visibility = Visible ? System.Windows.Visibility.Visible : System.Windows.Visibility.Collapsed;
            }
        }

        public bool Focused
        {
            get { return _focus || txtUrl.Focused; }
        }

        public void Dispose()
        {
            //throw new NotImplementedException();
        }

        #endregion

        public string GetSelectedText()
        {
            return this.txtUrl.SelectedText;
        }

        public void ReadOnly(bool readOnly)
        {
            this.txtUrl.IsReadOnly = readOnly;
        }

        public void OnMenu(ContextMenuEvent evt)
        {
            if (ContextMenuStrip.PREFERENCE_EVENT.Equals(evt.GetContextEvent()))
            {
                if (Model.MRole.GetDefault().IsShowPreference())
                {
                    //opens Value preference window
                    Framework.ValuePreference obj = Framework.ValuePreference.Start(_mField, GetValue());
                    if (obj != null)
                    {
                        obj.Show();
                    }
                }
                return;
            }
            else if ("Editor".Equals(evt.GetContextEvent()))
            {

                Framework.Editor editor = new Framework.Editor(Msg.GetMsg(Envs.GetCtx(), _mField.GetHeader(), true), _mField.GetFieldLength().ToString(), GetText(), this);
                editor.Closed += (s, e) =>
                {

                    bool? ret = editor.DialogResult;
                    if ((bool)ret)
                    {
                        _focus = true;
                        this.SetValue(editor.GetText());

                        if (EditingControlDataGridView != null)
                        {
                            EditingControlDataGridView.RaiseCellValueChanged(this);
                            _mField.SetValue(this.Text);
                            ((DataUtil.DataObject)EditingControlDataGridView.SelectedItem).SetFieldValue(_columnName.ToUpper(), this.Text);
                        }
                        else
                        {
                            if (VetoableChangeListener != null)
                            {
                                VetoableChangeListener(this, EventArgs.Empty);
                            }

                        }
                        SetColor();
                        _focus = false;
                    }
                };

                editor.Show();
            }
        }

        public VDataGrid EditingControlDataGridView
        {
            get;
            set;
        }

        public void SetValueInDataGridColumn(object value)
        {
            SetValue(value);
        }



    }
}
